package com.onion.utils.utils;

import com.onion.utils.support.exception.OnionException;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Random;

public class PasswordUtil {

    private static final char[] character = new char[] {'1','2','3','4','5',
            '0','1','2','3','4','5','6','7','8','9',
            'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
            'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
    };

    /**
     * 生成指定长度随机密码
     * @return
     */
    public static String genRandomPswd(int len) {
        if(len < 8) {
            throw new OnionException(-1, "密码长度太短，长度最小8位！");
        }
        return genRandomPswd1(len);
    }

    /**
     * 生成指定长度随机密码
     * @return
     */
    protected static String genRandomPswd1(int len) {
        if(len < 8) {
            throw new OnionException(-1, "密码长度太短，长度最小8位！");
        }
        Random random = new Random();
        char specialChar = character[random.nextInt(5)];
        char digitChar = character[random.nextInt(10)+5];
        char lowercaseChar = character[random.nextInt(26)+15];
        char uppercaseChar = character[random.nextInt(26)+41];
        StringBuffer strb = new StringBuffer().append(lowercaseChar).append(uppercaseChar);
        int randomLenth = len - 4;
        for(int i=0; i<randomLenth; i++) {
            strb.append(character[random.nextInt(67)]);
        }
        strb.append(digitChar).append(specialChar);
        return strb.toString();
    }

    /**
     * 密码加密
     * @param username
     * @param srcPswd
     * @return
     */
    public static String encrypt(String username, String srcPswd) {
        return DigestUtils.md5Hex(username+srcPswd);
    }

    public static void main(String[] args){
        System.out.print(encrypt("test@dayima.com", "123qwe"));
    }

}